package com.lill.workflow.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;

@Configuration
@MapperScan(basePackages = { "com.lill.workflow.dao" }, sqlSessionTemplateRef = "businessWorkflowSessionTemplate")
public class BusinessWorkflowDataSourceConfig {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Bean(name = "businessWorkflowDataSource")
	@ConfigurationProperties(prefix = "spring.datasource.business-workflow")
	public DataSource setDataSource() {
		return DruidDataSourceBuilder.create().build();
	}

	@Bean(name = "businessWorkflowTransactionManager")
	public DataSourceTransactionManager setTransactionManager(@Qualifier("businessWorkflowDataSource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean(name = "businessWorkflowSqlSessionFactory")
	public SqlSessionFactory setSqlSessionFactory(@Qualifier("businessWorkflowDataSource") DataSource dataSource) {
		try {
			SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
			bean.setDataSource(dataSource);
			bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapping/business-workflow/*.xml"));
			bean.setTypeAliasesPackage("com.lill.workflow.model");
//			bean.
			bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
			bean.getObject().getConfiguration().setCacheEnabled(true);
			return bean.getObject();
		} catch (Exception e) {
			logger.error("businessWorkflowSqlSessionFactory is error!", e);
		}
		return null;
	}

	@Bean(name = "businessWorkflowSessionTemplate")
	public SqlSessionTemplate setSqlSessionTemplate(@Qualifier("businessWorkflowSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
		return new SqlSessionTemplate(sqlSessionFactory);
	}

}
